//  我的-部门认证
const baseUrl = 'https://gsdse.cn/api/KJRecruit';
const app = getApp();


Page({

  /**
   * 页面的初始数据
   */

  data: {
    Department: ['秘书处', '网络研发部', '影视部', '动画部', 'PC技术部', '新媒体运营部', 'UI设计部'],
    position: ['主席', '副主席', '正部长', '副部长', '干事'],
    departmentName: '请选择部门',
    positionName: '请选择职位',
    AuthenticationCode: '',
    position_index: '',
    Department_index: '',
    departmentId: '',
    department: '',
    Position: '',
    password: '',
    personInfo: {},
  },

  // ----------------------------------
  // methods
  _ChooseDepartment(e) {
    this.setData({
      departmentName: '',
      Department_index: e.detail.value,
    });
    // console.log("Department_index", this.data.Department_index)
    this.setData({
      departmentId: ++this.data.Department_index,
    })
    console.log("this.data.departmentId", this.data.departmentId)

  },
  _ChoosePosition(e) {
    // console.log(e);
    this.setData({
      positionName: this.data.position[e.detail.value],
      position_index: e.detail.value,
    });
    // console.log(this.data.positionName)
  },

  AuthenticationCode(e) {
    this.setData({
      AuthenticationCode: e.detail.value
    })
    console.log("认证码", this.data.AuthenticationCode)
  },

  async authentication() {
    this.setData({
      Position: this.data.position[this.data.position_index],
    });
    // console.log("职位", this.data.Position)
    // console.log("userId", this.data.personInfo.userId)
    let departmentId = this.data.departmentId;
    let Position = this.data.Position;
    let AuthenticationCode = this.data.AuthenticationCode;
    let userId = this.data.personInfo.userId;
    if (departmentId == 0 || Position == 0 || AuthenticationCode == 0) {
      wx.showToast({
        icon: 'none',
        title: '未填写全部信息',
      })
    } else if (userId == undefined) {
      wx.showToast({
        icon: 'none',
        title: '未登录',
      })
    } else if (getApp().data.personInfo.departmentId != departmentId) {
      getApp().showError("部门选择错误")
      return;
    } else {
      const isOk = await this.certificationSuccess()
      if (isOk) { //保存用户信息
        const userInfo = await this.storageUserInfo(userId)
        //给部长权限
        console.log(this.data.positionName)
        if (this.data.positionName != '干事') {
          console.log('获得部长权限')
          await this.updateUser(userInfo, 1)
        } else {
          console.log('辛苦了')
          await this.updateUser(userInfo, 0)
        }
      }
    }
  },

  //给部长权限
  updateUser(userInfo, positionName) {
    return new Promise((reslove, reject) => {
      wx.request({
        url: baseUrl + '/updateUser',
        method: 'POST',
        header: {
          "Content-Type": "application/json"
        },
        data: {
          userId: userInfo.userId,
          applyId: userInfo.applyId,
          userName: userInfo.userName,
          phoneNumber: userInfo.phoneNumber,
          email: userInfo.email,
          positionName: positionName,
          position: userInfo.position,
          departmentId: userInfo.departmentId,
          schoolClass: userInfo.schoolClass,
          wxuserId: userInfo.wxuserId,
        },
        success: function (res) {
          console.log('修改成功')
          wx.hideLoading();
          wx.showToast({
            title: '保存成功',
          });
          reslove()
        },
        fail: function (res) {
          wx.hideLoading();
          console.log(res);
          wx.showToast({
            title: '保存失败',
          })
        }
      })
    })
  },

  //保存用户信息
  storageUserInfo(userId) {
    return new Promise((reslove, reject) => {
      wx.request({
        url: baseUrl + '/selectUser',
        method: 'POST',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
          userId: userId
        },
        success: function (res) {
          reslove(res.data.data)
        }
      })
    })
  },

  //认证成功
  certificationSuccess() {
    const that = this
    return new Promise((resolve, reject) => {
      wx.request({
        url: baseUrl + '/joindepartment',
        method: 'POST',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
          userId: that.data.personInfo.userId,
          identification: that.data.AuthenticationCode,
          departmentId: that.data.departmentId,
          position: that.data.Position,
        },
        success: async function (res) {
          let isOk = false;
          if (res.data.code == 0) {
            wx.showToast({
              icon: 'none',
              title: '认证成功',
            })
            // wx.switchTab({
            //   url: '../mine/mine',
            // })
            isOk = true
          } else if (res.data.code == 1) {
            wx.showToast({
              icon: 'none',
              title: '认证码错误',
            })
            resolve(false)
          }
          console.log("success", res)
          resolve(isOk)
        }
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    //获取全局变量personInfo
    this.setData({
      personInfo: getApp().data.personInfo
    })
    console.log("个人信息", this.data.personInfo)
    //检测是否完善个人资料
    const userInfo = await getApp().selectUser()
    const isInfoEdited = await getApp().IsPersonalInfoEdit(userInfo)
    if (!isInfoEdited) {
      wx.showModal({
        showCancel: false,
        title: '提示',
        content: '请先完善个人资料，以便您后续可以查询录取情况；如果本提示在编辑完资料后仍然出现，请尝试等待片刻并刷新小程序。',
        cancelColor: 'cancelColor',
        success: res => {
          if (res.confirm) {
            //点了确定
            wx.switchTab({
              url: '/pages/mine/mine',
            })
          }
        }
      })
    } else if (getApp().data.personInfo.departmentId === 0) {
      wx.showModal({
        showCancel: false,
        title: '提示',
        content: '您未加入任何部门，无法进行认证',
        cancelColor: 'cancelColor',
        success: res => {
          if (res.confirm) {
            //点了确定
            wx.switchTab({
              url: '/pages/mine/mine',
            })
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 深拷贝与浅拷贝
    //这里的业务场景 如果用了浅拷贝，就比较好！
    // this.setData({
    //   personInfo: app.personInfo

    // })
    // console.log(app.personInfo);


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})